/** sps_req_factroy.cpp - the implemention of factory for request message
 */


#include "sps_config.h"

#define INIT_AUTH_CODE         100
#define GET_USBKEY_ID          200
#define IS_USBKEY_EXIST        201
#define IS_USBKEY_VALID        202
#define USE_USBKEY_SIGN        203
#define DETECT_HEARTBEAT       600

SpsReq* SpsReqFactroy::loadRequest(const std::string& msg,
				   const std::string& ip,
				   const std::string& mac)
{
  SpsReq *req = NULL;
  json    v;
  int     code = -1;
  int     err = ESPS_SUCCESS;

  try {
    v = json::parse_string(msg);
    code = v[SJN_CODE].as_int();
  } catch (const json_exception& e) {
    SpsLog::instance().logError("parse json request failed (%s)", e.what());
    err = ESPS_PARSE_FAILED;
    goto ERR_EXIT;
  }

  switch (code) {

  case INIT_AUTH_CODE:
    req = new SpsAuthReq(ip, mac);
    break;

  case IS_USBKEY_EXIST:
    req = new SpsExistReq(ip, mac);
    break;

  case IS_USBKEY_VALID:
    req = new SpsValidReq(ip, mac);
    break;

  case GET_USBKEY_ID:
    req = new SpsUidReq(ip, mac);
    break;

  case USE_USBKEY_SIGN:
    req = new SpsSignReq(ip, mac);
    break;

  case DETECT_HEARTBEAT:
    req = new SpsHeartReq(ip, mac);
    break;

  default:
    SpsLog::instance().logError("invalid type of operation");
    err = ESPS_INVALID_OPERATION;
    goto ERR_EXIT;
  }

  req->set_err(err);
  req->set_req(v);

  return req;

 ERR_EXIT:
  
  req = new SpsReq(ip, mac);
  req->set_err(err);

  return req;
}
